<template>
  <a-drawer
      :title="title"
      :maskClosable="true"
      :visible="visible"
      :destroyOnClose="true"
      :width="700"
      :body-style="{ paddingBottom: '80px' }"
      @close="closeModal"
  >
    <div class="header-box">
      <!--  头像  -->
      <a-avatar v-if="detail.avatar" :size="56" :src="detail.avatar">
      </a-avatar>
      <a-avatar v-else :size="56" class="bg-primary">
        {{ getName(detail.realname) }}
      </a-avatar>
      <!--  描述  -->
      <div class="header-dec">
        <div>
          <span class="dec-name">{{ detail.realname }}</span>
          <a-tag :color=" detail.status === 1 ? '#87d068' : detail.status === 3 ? '#faad14' : '#87d068' " >
            {{ detail.status === 1 ? "正常" : detail.status === 3 ? "未激活" : "" }}
          </a-tag>
        </div>
        <div class="dec-gray">
          <span>工号：{{ detail.job_number }}</span>
          <span style="margin-left: 15px;" v-if="detail.position">职务：{{ detail.position }}</span>
          <span style="margin-left: 15px;" v-if="detail.departmentData && detail.departmentData.labelTips.length > 0">
            部门：
            <span v-for="(item, index) of detail.departmentData && detail.departmentData.labelTips">
              {{ item }}<span v-if="index != detail.departmentData.labelTips.length - 1 ">,</span>
            </span>
          </span>
        </div>
      </div>
    </div>

    <div v-if="type == 2" style="margin-top: 10px">
      <div style="margin-bottom: 5px;">选择要转移的资源</div>
      <div style="width: 100%;">
        <a-checkbox-group v-model:value="transferlist" @change="checkboxgroup" name="checkboxgroup" >
          <a-row>
            <a-col v-for="(item , index) in plainOptions" :key="index" :span="6">
              <a-checkbox :value="item.value">
                {{item.label}}
                <a-tooltip>
                  <template #title>包含待审批中的合同以及合同审批流中的设置</template>
                  <question-circle-outlined v-if="item.value == 6" />
                </a-tooltip>
              </a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </div>
    </div>

    <div style="margin-top: 10px">
      <div style="margin-bottom: 5px;">设置资源接收人</div>
      <div>
        <a-table
            class="mt-10"
            :dataSource="dataliat"
            :columns="columns"
            :loading="loading"
            :pagination="false"
        >
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'receive'">
              <div style="height: 40px;">
                <div style="display: flex;">
                  <div v-if="text" style="display: inline-block;width: 40px;height: 40px;line-height: 40px;background-color: #2681f3;border-radius: 30px;text-align: center;color: white;">
                    {{text.user[0].realname}}
                  </div>
                  <div v-if="text" style="display: inline-block;height: 40px;margin-left: 5px;">
                    <div style="height: 20px;">{{text.user[0].realname}}</div>
                    <div style="height: 20px;color: #999999;">{{text.user[0].position || '--'}}</div>
                  </div>
                  <div v-if="record.num > 0" @click="chooseDeptLeader(record.alias ,record.receive)" style="display: flex;height: 40px;margin-left: 15px;color: #2681f3;font-size: 20px;padding-top: 10px;cursor: pointer;">
                    <edit-outlined />
                  </div>
                  <div v-else style="display: flex;height: 40px;margin-left: 15px;color: #999999;font-size: 20px;padding-top: 10px;cursor: not-allowed;">
                    <edit-outlined />
                  </div>
                </div>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>



    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button v-if="type == 1" type="primary" :loading="submitLoading" @click.prevent="departes" >
        离职
      </a-button >
      <a-button v-else type="primary" :loading="submitLoading" @click.prevent="changees" >转移资源</a-button >
    </div>

    <!-- 选择部门负责人 -->
    <ChooseOrgMember
        :visible="chooseMemberVisible"
        :getDetail="true"
        :deptDisabled="true"
        :uMax="1"
        :checkedList="checkedApproverList"
        :setUids="'uncheck'"
        :uids="[id]"
        @request="$utils.commonRequest"
        @close="closeChooseMemberModal"
        @success="handleMemberSelect"
    />

  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Form, message, TreeSelect } from "ant-design-vue";
import { EditOutlined, QuestionCircleOutlined } from "@ant-design/icons-vue";
import { ChooseOrgMember } from "bl-common-vue3";
import store from "../../../../store";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import _ from "lodash";
import moment from "dayjs";
const plainOptions = [
  { label: '招商线索', value: 1 },
  { label: '招商客户', value: 2 },
  { label: '跟进合同', value: 3 },
  { label: '巡检任务', value: 4 },
  { label: '工单任务', value: 5 },
  { label: '合同审批', value: 6 },
  { label: '使用资产', value: 7 },
  { label: '资产管理员', value: 8 },
  { label: '业户招商跟进人', value: 9 },
]

const columns = [
  {
    title: "资源",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "描述",
    dataIndex: "desc",
    key: "desc",
  },
  {
    title: "接收方",
    dataIndex: "receive",
    key: "receive",
  },
]

export default defineComponent({
  name: "EditDepartment",
  components: { EditOutlined , ChooseOrgMember , QuestionCircleOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 当前员工id
    id: {
      type: [String, Number],
      default: 0,
    },
    department_id: {
      type: [String, Number],
      default: 0,
    },
    // 抽屉类型 1操作离职  2转移资源
    type: {
      type: [String, Number],
      default: 0,
    },

  },
  setup(props, context) {
    /**
     * @description: 标题显示
     */
    const title = computed(() => {
      return props.type == 1 ? "操作离职" : "转移资源";
    });



    const state = reactive({
      submitLoading : false,
      chooseMemberVisible : false,
      selectedMember : {},
      detail: {},
      transferlist: [],
      dataliat: [],
      loading: false,
      total: 0,
      alias:'',
      checkedApproverList:{},
    });

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      context.emit("closerefurbish");
    };

    const chooseDeptLeader = (alias , receive) => {
      state.alias = alias
      state.checkedApproverList = receive
      state.chooseMemberVisible = true;
    };

    // 关闭选择成员弹窗
    const closeChooseMemberModal = () => {
      state.chooseMemberVisible = false;
    };

    const handleMemberSelect = (data) => {
      for (let i = 0; i < state.dataliat.length; i++) {
        if(state.dataliat[i].alias == state.alias){
          state.dataliat[i].receive = data
        }
      }
      closeChooseMemberModal();
    };

    const getEditInfo = () => {
      request
          .get("/org", "/department/getUserDetail", {
            uid: props.id
          })
          .then((res) => {
            const { list } = res;
            state.detail = list;
          });
    };

    const getUserDetail = () => {
      request
          .post("/org", "/department/user/property/list", {
            selectedIndex: state.transferlist,
            user_id:props.id
          })
          .then((res) => {
            if(props.type == 1){
              state.dataliat = res.list
              for (let i = 0; i < state.dataliat.length; i++) {
                state.dataliat[i].receive = ''
              }
            }else {
              if(state.transferlist.length == 0){
                state.dataliat = []
              }else if(state.transferlist.length == 1){
                state.dataliat = res.list
                for (let i = 0; i < state.dataliat.length; i++) {
                  state.dataliat[i].receive = ''
                }
              }else {
                let list = res.list
                let data = state.dataliat
                for (let i = 0; i < list.length; i++) {
                  for (let j = 0; j < data.length; j++) {
                    if(list[i].alias == data[j].alias){
                      list[i].receive = data[j].receive
                    }
                  }
                }
                state.dataliat = list
                for (let i = 0; i < state.dataliat.length; i++) {
                  if(!state.dataliat[i].receive || !state.dataliat[i].receive.user ){
                    state.dataliat[i].receive = ''
                  }
                }
              }
            }

          });
    };

    const checkboxgroup = (checkedValue) => {
      console.log(checkedValue)
      console.log(state.transferlist)
      getUserDetail()
    }

    const getName = (name) => {
      if (!name) return;
      if (name.length > 2) {
        return name.slice(-2);
      } else {
        return name;
      }
    };

    const departes = () => {

      for (let i = 0; i < state.dataliat.length; i++) {
        if(state.dataliat[i].num > 0 && !state.dataliat[i].receive ){
          message.warn(`请选择 ${state.dataliat[i].name} 的资源接收人！`);
          return
        }
        if (state.dataliat[i].receive){
          state.dataliat[i].trans_user_id = state.dataliat[i].receive.user[0].uid
        }
      }

      utils.modalConfirm({
        title: "离职确认",
        content:
            "是否确认将该成员移出机构？该成员将不再允许登录，需要重新入职。",
        okType: "danger",
        centered: true,
        onOk: () => {
          request
              .del("/org", "/department/user", {
                uid: props.id,
                department_id: props.department_id,
                property_list: state.dataliat,
                needMsg: true,
              })
              .then((res) => {
                message.success(res.msg || "操作成功");
                context.emit("closerefurbish" , 'ok');
              });
        },
      });
    }
    
    const changees = () => {
      if(state.dataliat.length == 0 ){
        message.warn(`请选择需要转移的资源！`);
        return
      }
      let num = 0

      for (let i = 0; i < state.dataliat.length; i++) {
        if(state.dataliat[i].num > 0 && !state.dataliat[i].receive ){
          message.warn(`请选择 ${state.dataliat[i].name} 的资源接收人！`);
          return
        }
        if (state.dataliat[i].receive){
          state.dataliat[i].trans_user_id = state.dataliat[i].receive.user[0].uid
        }
        if(state.dataliat[i].num > 0 ){
          num++
        }
      }

      if(num == 0){
        message.warn(`暂无可转移资源！`);
        return
      }

      request
          .post("/org", "/department/user/property/trans", {
            property_list: state.dataliat,
            user_id:props.id
          })
          .then((res) => {
            message.success(res.msg || "操作成功");
            context.emit("closerefurbish" , 'ok');
          });
    }


    /**
     * @description: 初始化
     */
    const init = () => {
      getEditInfo()
      if(props.type == 1){
        getUserDetail()
      }

    };

    init()

    return {
      ...toRefs(state),
      title,
      columns,

      closeModal,
      init,
      chooseDeptLeader,
      closeChooseMemberModal,
      handleMemberSelect,
      getEditInfo,
      getName,
      plainOptions,
      checkboxgroup,
      getUserDetail,
      departes,
      changees,
    };
  },
});
</script>

<style lang="less" scoped>
.header-box {
  display: flex;
  margin-bottom: 10px;
}
.bg-primary {
  background-color: @primary-color;
  color: #fff;
  font-size: 16px;
}
.header-dec {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 10px;
  .dec-name {
    font-size: 16px;
    font-weight: bold;
    margin-right: 10px;
  }
  .dec-gray {
    padding-top: 5px;
    font-size: 14px;
    color: #6b6b6b;
  }
}
:deep(label.ant-checkbox-wrapper.ant-checkbox-group-item) {
  color: #666666;
}
</style>
